'use strict';
const url = require('url');
var vk; // 全局vk实例
// 涉及的表名
const dbName = {
	//test: "vk-test", // 测试表
};

var db = uniCloud.database(); // 全局数据库引用
var _ = db.command; // 数据库操作符
var $ = _.aggregate; // 聚合查询操作符
/**
 * 权限注意：访问以下链接查看
 * 文档地址：https://vkdoc.fsq.pub/client/uniCloud/cloudfunctions/cloudObject.html#内置权限
 */
var cloudObject = {
	isCloudObject: true, // 标记为云对象模式
	/**
	 * 请求前处理，主要用于调用方法之前进行预处理，一般用于拦截器、统一的身份验证、参数校验、定义全局对象等。
	 * 文档地址：https://vkdoc.fsq.pub/client/uniCloud/cloudfunctions/cloudObject.html#before-预处理
	 */
	_before: async function() {
		vk = this.vk; // 将vk定义为全局对象
		// let { customUtil, uniID, config, pubFun } = this.getUtil(); // 获取工具包
	},
	/**
	 * 请求后处理，主要用于处理本次调用方法的返回结果或者抛出的错误
	 * 文档地址：https://vkdoc.fsq.pub/client/uniCloud/cloudfunctions/cloudObject.html#after-后处理
	 */
	_after: async function(options) {
		let {
			err,
			res
		} = options;
		if (err) {
			return; // 如果方法抛出错误，直接return;不处理
		}
		return res;
	},
	/**
	 * 获取列表
	 * @url client/pub.lanzou.getList 前端调用的url参数地址
	 */
	getList: async function(data) {
		let res = {
			code: 0,
			msg: ''
		};
		let {
			customUtil,
			uniID,
			config,
			pubFun
		} = this.getUtil(); // 获取工具包

		let {
			uid
		} = this.getClientInfo(); // 获取客户端信息
		// 业务逻辑开始-----------------------------------------------------------


		// 业务逻辑结束-----------------------------------------------------------
		return res;
	},
	/**
	 * 模板函数
	 * @url client/pub.lanzou.parse 前端调用的url参数地址
	 */
	parse: async function(data) {
		let res = {
			code: -1,
			msg: '未知错误'
		};
		let {
			uid
		} = this.getClientInfo(); // 获取客户端信息
		let {
			customUtil,
			uniID,
			config,
			pubFun
		} = this.getUtil(); // 获取工具包

		// 业务逻辑开始-----------------------------------------------------------
		// 测试地址：https://wwxh.lanzoum.com/icWlG1cwtzyj
		// https://wwxh.lanzoum.com/i1l091cwtn0d test1
		let header = {

		}
		let {
			url: link,
			pwd,
			filetype = "file",
			pgs=1
		} = data;
		if (vk.pubfn.isNull(link)) {
			return {
				code: -1,
				msg: "解析地址不能为空"
			}
		}
		let filename, filesize, fn, zturl, pwdsign, uploadtime, shareUser;

		const parsedUrl = url.parse(link);
		const path = parsedUrl.pathname;
		if (path.startsWith('/i')) {
			filetype = "file"
		} else if (path.startsWith('/b')) {
			filetype = "dir"
		}

		let requestRes = await vk.request({
			method: 'GET',
			url: link,
			header: {
				"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36",
				"Content-Type": "application/x-www-form-urlencoded"
			},
			dataType: "text"
		});
		console.log(requestRes)
		if (vk.pubfn.isNotNull(pwd)) {
			if (filetype == "file") {
				pwdsign = pubFun.subStringMulti(requestRes, 'skdklds = \'', '\';').toString()
				filesize = pubFun.subStringMulti(requestRes, '">大小：', '</div>').toString()
				uploadtime = pubFun.subStringMulti(requestRes, '上传时间：</span>', '<br>').toString()
				shareUser = pubFun.subStringMulti(requestRes, '分享用户：</span><font>', '</font><br>').toString()
				if (pwdsign == '') {
					return {
						code: -1,
						msg: '获取sign失败,请检查文件是否存在.'
					}
				}
				let ajaxmRequestRes = await vk.request({
					method: 'POST',
					url: "https://wwc.lanzoub.com/ajaxm.php",
					header: {
						"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36",
						"referer": link
					},
					data: {
						action: 'downprocess',
						sign: pwdsign,
						p: pwd
					},
					dataType: "json"
				});
				if (ajaxmRequestRes.zt != 1) {
					return {
						code: -1,
						msg: "解析失败"
					}
				}
				console.log("ajaxmRequestRes", ajaxmRequestRes)
				filename = ajaxmRequestRes.inf
				zturl = ajaxmRequestRes.dom + '/file/' + ajaxmRequestRes.url
				return {
					"code": 0,
					"filetype": filetype,
					"filename": filename,
					"filesize": filesize,
					"uploadtime": uploadtime,
					"shareUser": shareUser,
					"durl": zturl,
					"msg": "解析成功"
				}
			} else {
				let parse_lx = pubFun.subStringMulti(requestRes, '\'lx\':', ',')[0].toString()
				let parse_fid = pubFun.subStringMulti(requestRes, '\'fid\':', ',')[0].toString()
				let parse_uid = pubFun.subStringMulti(requestRes, '\'uid\':\'', '\',')[0].toString()
				let parse_rep = pubFun.subStringMulti(requestRes, '\'rep\':\'', '\',')[0].toString()
				let pre_parse_t = pubFun.subStringMulti(requestRes, '\'t\':', ',')[0].toString()
				let pre_parse_k = pubFun.subStringMulti(requestRes, '\'k\':', ',')[0].toString()
				let parse_t = pubFun.subStringMulti(requestRes, pre_parse_t + ' = \'', '\'')[0].toString()
				let parse_k = pubFun.subStringMulti(requestRes, pre_parse_k + ' = \'', '\'')[0].toString()
				let parse_up = pubFun.subStringMulti(requestRes, '\'up\':', ',')[0].toString()
				let parse_ls = pubFun.subStringMulti(requestRes, '\'ls\':', ',')[0].toString()
				
				if (!parse_t || !parse_k) {
					return {
						code: -1,
						msg: '参数解析失败,请检查文件夹是否存在.'
					}
				}
				let ajaxmRequestRes = await vk.request({
					method: 'POST',
					url: "https://wwc.lanzoub.com/filemoreajax.php",
					header: {
						"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36",
						"referer": link
					},
					data: {
						'lx': parse_lx,
						'fid': parse_fid,
						'uid': parse_uid,
						'pg': pgs,
						'rep': parse_rep,
						't': parse_t,
						'k': parse_k,
						'up': parse_up,
						'ls': parse_ls,
						'pwd': pwd
					},
					dataType: "json"
				});
				if (ajaxmRequestRes.zt != 1) {
					return {
						code: -1,
						msg: "解析失败"
					}
				}
				let text = ajaxmRequestRes.text;
				// [{
				// 	"icon": "pdf",
				// 	"t": 0,
				// 	"id": "igIc81dme83c",
				// 	"name_all": "044002300411_79172455.pdf",
				// 	"size": "37.7 K",
				// 	"time": "1 小时前",
				// 	"duan": "i1dme83",
				// 	"p_ico": 0
				// }]
				let fileslist = [];
				text.forEach(item => {
					fileslist.push({
						icon: "https://assets.woozooo.com/assets/images/filetype/"+item.icon + ".gif",
						url: "https://wwxh.lanzoum.com/" + item.id,
						size: item.size,
						time: item.time,
						duan: item.duan,
						name: item.name_all
						
					})
				})
				return {
					"code": 0,
					"filetype": filetype,
					"data": fileslist,
					"msg": "解析成功"
				}
				
			}
		} else {
			/**
			 * 无密码解析
			 */
			fn = pubFun.subStringMulti(requestRes, "/fn?", "\"")[3].toString()

			if (vk.pubfn.isNull(fn)) {
				return {
					code: -1,
					msg: '无法获取fn,请检查文件是否存在或是否需要密码访问.'
				}
			}
			filename = pubFun.subStringMulti(requestRes, "56px 0px 20px 0px;\">", "</div>").toString()
			filesize = pubFun.subStringMulti(requestRes, '文件大小：</span>', '<br>').toString()
			uploadtime = pubFun.subStringMulti(requestRes, '上传时间：</span>', '<br>').toString()
			shareUser = pubFun.subStringMulti(requestRes, '分享用户：</span><font>', '</font><br>').toString()
			let sendurl = 'https://wwc.lanzoub.com/fn' + fn
			let sendRequestRes = await vk.request({
				method: 'GET',
				url: sendurl,
				header: {
					"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36",
					"Content-Type": "application/x-www-form-urlencoded"
				},
				dataType: "text"
			});
			let websignkey = pubFun.subStringMulti(sendRequestRes, 'aihidcms = \'', '\';').toString()
			let sign = pubFun.subStringMulti(sendRequestRes, '\'sign\':\'', '\',').toString()

			if (websignkey == '' || sign == '') {
				return {
					code: -1,
					msg: '请检查文件是否存在或是否需要密码访问,若一切正常请到 https://www.ilzya.com/archives/4 提交更新'
				}
			}

			let ajaxmRequestRes = await vk.request({
				method: 'POST',
				url: "https://wwc.lanzoub.com/ajaxm.php",
				header: {
					"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36",
					"referer": sendurl
				},
				data: {
					action: 'downprocess',
					sign,
					websign: "",
					websignkey,
					ves: 1
				},
				dataType: "json"
			});
			if (ajaxmRequestRes.zt == 0) {
				return {
					code: -1,
					msg: "解析失败"
				}
			}
			console.log("ajaxmRequestRes", ajaxmRequestRes)
			zturl = ajaxmRequestRes.dom + '/file/' + ajaxmRequestRes.url
			return {
				"code": 0,
				"filetype": filetype,
				"filename": filename,
				"filesize": filesize,
				"uploadtime": uploadtime,
				"shareUser": shareUser,
				"durl": zturl,
				"msg": "解析成功"
			}
		}

		// 业务逻辑结束-----------------------------------------------------------
		return res;
	},
};

module.exports = cloudObject;